package com.pospi.xstore.ui.caigou;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.dto.SearchBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DownUtil;
import com.pospi.xstore.util.GetData;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

public class ReceiveBillListActivity extends BaseActivity {
    @Bind(R.id.total_je)
    TextView total_je;
    @Bind(R.id.bill_num)
    TextView bill_num;
    @Bind(R.id.switch_button)
    SwitchMultiButton switch_button;
    @Bind(R.id.tv_list_title)
    TextView tv_list_title;
    @Bind(R.id.iv_search_counts)
    ImageView iv_search_counts;
    @Bind(R.id.bill_num_title)
    LinearLayout bill_num_title;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private int page = 1;

    private List<CgddBeen> beens = new ArrayList<>();
    private String count;
    private String je;
    private MyAdapter adapter;
    private String billno;
    private String market;
    private String supid;
    private String num;
    private String barcode;
    private String status;
    private SearchBeen searchBeen;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_cgdd_list);
        ButterKnife.bind(this);
        setTitle("采购收货单");
        setMenuImage(R.drawable.add);
        new DownUtil(this).downMsg();
        init();
    }
    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        Intent intent = new Intent(this, ReceiveDetailActivity.class);
        startActivity(intent);

    }



    private void init() {
        refreshLayout.setEnableRefresh(false);//禁止下拉
        refreshLayout.setEnableLoadMore(true);//开启上拉
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);//是否在列表不满一页时候开启上拉加载功能
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                loadMore(page);
            }
        });
        iv_search_counts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ReceiveBillListActivity.this, CgddActivity.class);
                intent.putExtra("mark", "cgsh");
                startActivity(intent);
            }
        });
        switch_button.setText("今天","昨天","近三天","所有");
        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                initRefresh();
                switch (position) {
                    case 0:
                        startrq = GetData.getAnyTime(0);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 1:
                        startrq = GetData.getAnyTime(1);
                        endrq = GetData.getAnyTime(1);
                        searchBillfast();
                        break;
                    case 2:
                        startrq = GetData.getAnyTime(3);
                        endrq = GetData.getAnyTime(0);
                        searchBillfast();
                        break;
                    case 3:
                        startrq = "";
                        endrq = "";
                        searchBillfast();
                        break;
                }
            }
        });
        tv_list_title.setText("没有查询到数据");

        ListView bill_list = (ListView) findViewById(R.id.list_bill);
        adapter = new MyAdapter();
        bill_list.setAdapter(adapter);
        bill_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(ReceiveBillListActivity.this, ReceiveDetailActivity.class);
                intent.putExtra("data", beens.get(i));
                startActivity(intent);
            }
        });
        searchBillfast();

    }

    private void loadMore(int page) {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", Constant.BILL_MODE_CGRK);
        params.put("type", Constant.BILL_TYPE_CGRK);
        params.put("fun", "find_list");

        params.put("page", page);
        params.put("limit", "20");


        JSONObject object = new JSONObject();
        try {
            object.put("startrq", startrq);
            object.put("endrq", endrq);
            object.put("billno", billno);
            object.put("market", market);
            object.put("supid", supid);
            object.put("num", num);
            object.put("barcode", barcode);
            object.put("status", status);
//            object.put("filter", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    List<CgddBeen> cgddBeens = new Gson().fromJson(result.toString(),
                            new TypeToken<List<CgddBeen>>() {
                            }.getType());
                    if (cgddBeens.size() == 0) {
                        refreshLayout.setNoMoreData(true);
                    }
                    beens.addAll(cgddBeens);
                    Message message = Message.obtain();
                    message.what = RE_LOADMORE;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch_button.clearSelection();
        beens.clear();
        searchBeen = (SearchBeen) intent.getSerializableExtra("data");
        if (searchBeen != null) {
            startrq = searchBeen.getStartRq();
            endrq = searchBeen.getEndRq();
            billno = searchBeen.getBillno();
            market = searchBeen.getMarket();
            supid = searchBeen.getSupid();
            num = searchBeen.getNum();
            barcode = searchBeen.getBarcode();
            status = searchBeen.getStatus();

            initRefresh();
        }
        searchBillfast();
    }
    private void initRefresh(){
        page = 1;
        refreshLayout.setNoMoreData(false);
    }

    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return beens.size();
        }

        @Override
        public Object getItem(int i) {
            return beens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder ;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(ReceiveBillListActivity.this).inflate(R.layout.cgdd_list_item, null);
                holder.statusname = view.findViewById(R.id.statusname);
                holder.billno = view.findViewById(R.id.billno);
                holder.je = view.findViewById(R.id.je);
                holder.billrq = view.findViewById(R.id.billrq);
                holder.marketname = view.findViewById(R.id.marketname);
                holder.supname = view.findViewById(R.id.supname);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            CgddBeen cgddBeen = beens.get(i);
            holder.supname.setText(cgddBeen.getSupname());
            holder.statusname.setBackgroundResource(cgddBeen.getStatusname().equals(Constant.BILL_TYPE_WSH)
                    ?R.drawable.icon_chart_wsh:R.drawable.icon_chart_ysh);
            holder.marketname.setText(cgddBeen.getMarketname());
            holder.billrq.setText(cgddBeen.getBillrq());
            holder.billno.setText(cgddBeen.getBillno());
            holder.je.setText(cgddBeen.getJe());

            return view;
        }
        class Holder{
            TextView statusname;
            TextView billno;
            TextView je;
            TextView billrq;
            TextView marketname;
            TextView supname;

        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RE_SUCESS:
                    getNetData((String) msg.obj);
                    break;
                case RE_NOPARSING:

                    break;
                case RE_FAILED:

                    break;
                case RE_LOADMORE:
                    //加载更多
                    refreshLayout.finishLoadMore(true);
                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    };

    private void getNetData(String obj) {
        try {
            JSONObject jsonObject = new JSONObject(obj);
            JSONArray result = jsonObject.getJSONArray("result");
            Log.i("login", jsonObject.getString("errMsg"));
            List<CgddBeen> cgddBeens = new Gson().fromJson(result.toString(),
                    new TypeToken<List<CgddBeen>>() {
                    }.getType());
            beens.clear();
            beens.addAll(cgddBeens);
            JSONObject sumrow = jsonObject.getJSONObject("sumrow");
            count = sumrow.getString("count");
            je = sumrow.getString("je");
        } catch (JSONException e) {

            e.printStackTrace();
        }
        if (beens.size() == 0) {
            setbill(false);
            adapter.notifyDataSetChanged();
        } else {
            setbill(true);
            adapter.notifyDataSetChanged();
        }
    }

    private void setbill(boolean o){
        if (o) {
            bill_num_title.setVisibility(View.VISIBLE);
            tv_list_title.setText("总合计金额");
            total_je.setText(je);
            bill_num.setText("" + count );
        } else {
            tv_list_title.setText("没有查询到数据");
            total_je.setText("");
            bill_num.setText("");
            bill_num_title.setVisibility(View.INVISIBLE);
            beens.clear();
            adapter.notifyDataSetChanged();
        }

    }



    private String startrq = GetData.getAnyTime(0);
    private String endrq = GetData.getAnyTime(0);
    private void searchBillfast() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", Constant.BILL_MODE_CGRK);
        params.put("type", Constant.BILL_TYPE_CGRK);
        params.put("fun", "find_list");
        params.put("page", 1);
        params.put("limit", "20");

        JSONObject object = new JSONObject();
        try {
            object.put("startrq", startrq);
            object.put("endrq", endrq);
            object.put("billno", billno);
            object.put("market", market);
            object.put("supid", supid);
            object.put("num", num);
            object.put("barcode", barcode);
            object.put("status", status);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        requestNet(params, handler);
    }

}
